<?php

namespace Serve\Controller;

use Common\Controller\NormalApiController;
use Serve\Utils\JWTToken;
use Think\Controller;


class VerifyController extends NormalApiController
{

    public function token()
    {
        $token = JWTToken::parseToken($_POST['token']);
        if ($token['expire'] < time()) {
            ClientError('令牌过期', C('CODE.FORBIDDEN')['code']);
        }
        Success(200);
    }

    /**
     * JWT 解析token对比数据库 id和username,
     * 存在此用户，若改用户未认证，进行认证，否则返回已认证
     */
    public function user()
    {
        $token = $this->_request['token'];
        $user = get_object_vars(\JWT::decode($token, C('JWT.key')));
        $model = $this->_db->users;
        if ($user = $model->find($user['userId'])) {
            if ($user['role'] != 0)
                ClientError('用户已经通过验证', C('CODE.FORBIDDEN')['code']);
            else {
                $model->role->update($user['userId'], 1);
                Success(200, '验证成功');
            }
        } else {
            ClientError('用户不存在', C('CODE.NOT_FOUND')['code']);
        }
    }

    /**
     * JWT 解析token对比数据库 id和username,
     * 存在此用户
     */
    public function password()
    {
        $token = $this->_request['token'];
        $username = $this->_request['username'];
        $password = $this->_request['password'];
        $user = get_object_vars(\JWT::decode($token, C('JWT.key')));
        $model = $this->_db->users;
        if ($user = $model->find($user['userId'])) {
            if ($user['role'] == 0)
                ClientError('未通过邮箱验证', C('CODE.FORBIDDEN')['code']);
            else {
                $model->auth->update([
                    'username' => $username,
                    'password' => md5($password)
                ]);
                Success(200, '更改成功');
            }
        } else
            ClientError('用户不存在', C('CODE.NOT_FOUND')['code']);
    }
}